﻿namespace RS.CmeFastHandler
{
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Configuration;
	using System.IO;
	using System.Text;
	using System.Threading;

	public class Handle
	{


		protected bool connectFlag = false;

		//protected ConnectionAddress address;
		protected bool downloadSecurityDefinition;
		protected Listener incrementDataListener;
		protected Thread incrementDataThread;
		protected Queue incrementQueue = new Queue();
		protected int incrementSeq = 0;
		protected bool matchedFlag = false;
		protected int securityCount = 0;

		//protected ArrayList securityDefinitionDicList = new ArrayList();
		protected String securityDefinitionDicString = ",";
		protected Listener securityDefinitionListener;
		protected Thread securityDefinitionThread;
		protected bool snapshotCompleted = false;
		protected int snapshotCount = 0;
		protected ArrayList snapshotDicList = new ArrayList();
		protected Listener snapshotListener;
		protected Thread snapshotThread;
		protected int tempSecurityCount = 0;

		//protected event System.EventHandler<RsMessageEventArgs> IncrementDataReceived;
		protected EventWaitFlags waitFlag = new EventWaitFlags();

		Dictionary<string, RsIncrementEventArgs> incrementDic = new Dictionary<string, RsIncrementEventArgs>();
		Dictionary<string, OpenFAST.Message> msgDic = new Dictionary<string, OpenFAST.Message>();





		public Handle()
		{
			downloadSecurityDefinition = true;
			lock (this)
			{
				Common.CONFIGFILE = Path.Combine(System.Environment.CurrentDirectory, ConfigurationManager.AppSettings["CMEFastConfig"]);
				Common.TEMPLATEFILE = Path.Combine(System.Environment.CurrentDirectory, ConfigurationManager.AppSettings["CMEFastTemplates"]);
				Common.InitCommon();
			}
		}



		#region Events

		public event System.EventHandler<RsErrorEventArgs> RS_ErrorReceived;

		public event System.EventHandler<RsIncrementEventArgs> RS_IncrementDataReceived;

		public event System.EventHandler<RsInfoEventArgs> RS_InfoReceived;

		// Event interface for UI
		public event System.EventHandler<RsSDEventArgs> RS_SecurityDefinitionReceived;

		public event System.EventHandler<RsSnapshotEventArgs> RS_SnapShotDataReceived;

		public event System.EventHandler<RsStatusEventArgs> RS_StatusChanged;

		#endregion Events

		#region Properties

		public string ChannelId
		{
			get;
			set;
		}

		#endregion Properties



		public void ProcessIncrementData(OpenFAST.Message msg)
		{
			lock (incrementQueue)
			{
				#region 保持数据的唯一性和完整性

				int tempCurrentSeq = int.Parse(msg.GetValue("MsgSeqNum").ToString());
				if (0 == incrementSeq)
				{
					incrementSeq = tempCurrentSeq;
				}
				else
				{
					if (incrementSeq == tempCurrentSeq)
					{
						// 数据重复，放弃此数据
						return;
					}
					else if (incrementSeq + 1 == tempCurrentSeq)
					{
						// 数据吻合，处理此数据
					}
					else if (incrementSeq + 1 < tempCurrentSeq)
					{
						// 如果大则意味着丢包，给客户端发送一个丢包错误，然后继续处理此数据
						RsErrorEventArgs args = new RsErrorEventArgs();
						args.ChannelId = ChannelId;
						args.Message = " Lost data:" + incrementSeq.ToString() + "-" + tempCurrentSeq.ToString();
						if (this.RS_ErrorReceived != null)
						{
							this.RS_ErrorReceived(this, args);
						}
					}
					else
					{
						// 其他情况 ， 比如新值小于当前值则放弃此数据
						return;
					}
				}
				incrementSeq = tempCurrentSeq;

				#endregion

				#region 处理Increment data 数据

				// 放到queue 的原因是为了snapshot对应。
				if (msg.Template.Name != "MDHeartbeat")
				{
					// 如果 Sanpshot 数据还没有完全获取则放到Queue里面，若已完成则直接发送给客户端。
					if (snapshotCompleted == false)
					{
						incrementQueue.Enqueue(msg);
					}
					else
					{
						// finished the snapshot process
						while (incrementQueue.Count > 0)
						{
							RsIncrementEventArgs args = new RsIncrementEventArgs();
							args.ChannelId = ChannelId;
							args.Message = (OpenFAST.Message)incrementQueue.Dequeue();
							if (this.RS_IncrementDataReceived != null)
							{
								this.RS_IncrementDataReceived(this, args);
							}
						}
						RsIncrementEventArgs inArgs = new RsIncrementEventArgs();
						inArgs.ChannelId = ChannelId;
						inArgs.Message = msg;
						if (this.RS_IncrementDataReceived != null)
						{
							this.RS_IncrementDataReceived(this, inArgs);
						}
					}
				}
				else
				{
					// Heartbeat data
					RsInfoEventArgs infoArgs = new RsInfoEventArgs();
					infoArgs.ChannelId = ChannelId;
					infoArgs.Message += " Heartbeat:" + msg.ToString();
					if (this.RS_InfoReceived != null)
					{
						this.RS_InfoReceived(this, infoArgs);
					}
				}
				#endregion
			}
		}

		// Start to recieve packge
		public virtual void Start()
		{
			// Set status
			RsStatusEventArgs args = new RsStatusEventArgs();
			args.ChannelId = ChannelId;
			args.Message = HandlerState.SecurityDefinitionsRecoveryStarted.ToString();
			if (this.RS_StatusChanged != null)
			{
				this.RS_StatusChanged(this, args);
			}
			// 开始下载标记
			connectFlag = true;
			RecieveSecurityDefinition();
			// Get Snapshot data
			RecieveSnapShotData();
			// Get Increment data
			RecieveIncrementData();
		}

		// Start to receive security definition
		public void StartDownloadSecurityDefinition()
		{
			// Set status
			//securityDefinitionDicList.Clear();
			RsStatusEventArgs args = new RsStatusEventArgs();
			args.ChannelId = ChannelId;
			args.Message = HandlerState.SecurityDefinitionsRecoveryStarted.ToString();
			if (this.RS_StatusChanged != null)
			{
				this.RS_StatusChanged(this, args);
			}
			// Subcribe evnet of security definition
			//this.SecurityDefinitionReceived += new EventHandler<RsMessageEventArgs>(Handler_SecurityDefinitionReceived);
			// Download Security Definition
			RecieveSecurityDefinition();
		}

		// Stop receive packge
		public void Stop()
		{
			Thread thread = new Thread(new ThreadStart(this.StopListen));
			thread.Start();
			thread.Join();
			Thread.Sleep(2000);
			if (securityDefinitionListener != null)
			{
				securityDefinitionListener.UdpQueue.Clear();
				tempSecurityCount = 0;
				securityDefinitionDicString = ",";
				securityCount = 0;
			}
			if (snapshotListener != null)
			{
				snapshotListener.UdpQueue.Clear();
				snapshotDicList.Clear();
				snapshotCount = 0;
				matchedFlag = false;
				snapshotCompleted = false;
			}
			if (incrementDataListener != null)
			{
				incrementDataListener.UdpQueue.Clear();
				this.incrementQueue.Clear();
			}
		}

		protected virtual void DecodeIncrementDataQueue()
		{
			// 等待 Security Definition 下载完成后开始获取 Increment 数据
			if (downloadSecurityDefinition)
			{
				securityDefinitionThread.Join();
			}

			if (connectFlag == true)
			{
				// Receive scurity defination
				ConnectionInfo address = Common.GetAllAddress(ChannelId, CHANNELTYPE.I);
				incrementDataListener = new Listener(CHANNELTYPE.I.ToString(), address, waitFlag.EventIncremntData);
				incrementDataListener.Start();
				waitFlag.EventIncremntData.Set();
				// decode
				while (waitFlag.EventIncremntData.WaitOne(0, false))
				{

					byte[] buffer = (byte[])incrementDataListener.UdpQueue.Dequeue();
					OpenFAST.Message msg = Common.Decode2Msg(buffer);
					//Increment TradePrice and TradeSize
					if (msg != null && !msg.Template.Name.Contains("MDQuoteRequest") && !msg.Template.Name.Contains("MDHeartbeat") && !msg.Template.Name.Contains("MDSecurityStatus") && !msg.Template.Name.Contains("MDSecurityDefinition"))
					{
						OpenFAST.SequenceValue entries = msg.GetSequence("MDEntries");
						for (int i = 0; i < entries.Length; i++)
						{
							if (entries[i].GetValue("MDEntryType").ToString().Equals("2"))
							{
								lock (incrementDic)
								{
									string tempSecurityID = entries[i].GetValue("SecurityID").ToString();
									if (!incrementDic.ContainsKey(tempSecurityID))
									{
										RsIncrementEventArgs tmpArgs = new RsIncrementEventArgs();
										if (entries[i].GetValue("MDEntryPx") != null)
											tmpArgs.TradePrice = entries[i].GetValue("MDEntryPx").ToString();
										else
											tmpArgs.TradePrice = string.Empty;
										if (entries[i].GetValue("MDEntrySize") != null)
											tmpArgs.TradeSize = entries[i].GetValue("MDEntrySize").ToString();
										else
											tmpArgs.TradeSize = string.Empty;
										incrementDic[tempSecurityID] = tmpArgs;
									}
									else
									{
										RsIncrementEventArgs tmpArgs = incrementDic[tempSecurityID];
										if (entries[i].GetValue("MDEntryPx") != null)
											tmpArgs.TradePrice = entries[i].GetValue("MDEntryPx").ToString();
										if (entries[i].GetValue("MDEntrySize") != null)
											tmpArgs.TradeSize = entries[i].GetValue("MDEntrySize").ToString();
										incrementDic[tempSecurityID] = tmpArgs;
									}
								}
							}
						}
					}
				}
			}
		}

		protected void DecodeSecurityDefinitionQueue()
		{
			try
			{
				while (waitFlag.EventScuiryDefinition.WaitOne(0, false))
				{

					byte[] buffer = (byte[])securityDefinitionListener.UdpQueue.Dequeue();
					OpenFAST.Message msg = Common.Decode2Msg(buffer);
					//RsMessageEventArgs args = new RsMessageEventArgs(msg);
					//this.SecurityDefinitionReceived(this,args);
					if (msg != null)
					{
						lock (securityDefinitionDicString)
						{
							//OpenFAST.Message msg = e.Message;
							//第一步 获取他的协议数量 Get the maxsize
							if (0 == securityCount)
							{
								securityCount = int.Parse(msg.GetValue(7).ToString());
								RsInfoEventArgs infoArgs = new RsInfoEventArgs();
								infoArgs.ChannelId = ChannelId;
								infoArgs.Message = " Security definition size is:" + securityCount.ToString();
								if (this.RS_InfoReceived != null)
								{
									this.RS_InfoReceived(this, infoArgs);
								}
							}
							//count the message
							int key = int.Parse(msg.GetValue("SecurityID").ToString());
							// 判断时候获取了所有协议
							if (tempSecurityCount < securityCount)
							{
								/* */
								// 协议是否已存在
								if (-1 == securityDefinitionDicString.IndexOf("," + key + ","))
								{
									//securityDefinitionDicList.Add(key);
									securityDefinitionDicString += key + ",";
									tempSecurityCount++;
									//sdDictionary.Add(key, msg);
									RsSDEventArgs args = new RsSDEventArgs();
									args.ChannelID = ChannelId;
									args.SecurityId = key.ToString();
									args.SecurityDesc = msg.GetValue("SecurityDesc").ToString();
									args.Message = msg;
									if (this.RS_SecurityDefinitionReceived != null)
									{
										this.RS_SecurityDefinitionReceived(this, args);
									}
								}
							}
							else
							{
								StopDownloadSecurityDefinition();
								RsStatusEventArgs args = new RsStatusEventArgs();
								args.ChannelId = ChannelId;
								args.Message = HandlerState.SecurityDefinitionsRecoveryFinished.ToString();
								if (this.RS_StatusChanged != null)
								{
									this.RS_StatusChanged(this, args);
								}

							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				RsErrorEventArgs args = new RsErrorEventArgs();
				args.ChannelId = ChannelId;
				StringBuilder sb = new StringBuilder();
				sb.
				Append("StackTrace:").
				Append(ex.StackTrace).
				Append(Environment.NewLine).
				Append("Message:").
				Append(ex.Message).
				Append("anInnerException:").
				Append(ex.InnerException);
				args.Message = sb.ToString();
				if (this.RS_ErrorReceived != null)
				{
					this.RS_ErrorReceived(this, args);
				}
				Stop();
			}
		}

		protected virtual void DecodeSnapshotDataQueue()
		{
			try
			{
				// 等待 Security Definition 下载完成后开始获取 Snapshot 数据
				if (downloadSecurityDefinition)
				{
					securityDefinitionThread.Join();
				}

				if (connectFlag == true)
				{
					// Receive scurity defination
					ConnectionInfo address = Common.GetAllAddress(ChannelId, CHANNELTYPE.S);
					snapshotListener = new Listener(CHANNELTYPE.S.ToString(), address, waitFlag.EventSnapShot);
					snapshotListener.Start();
					waitFlag.EventSnapShot.Set();

					RsStatusEventArgs args = new RsStatusEventArgs();
					args.ChannelId = ChannelId;
					args.Message = HandlerState.BooksResynchronizationStarted.ToString();
					if (this.RS_StatusChanged != null)
					{
						this.RS_StatusChanged(this, args);
					}
					while (waitFlag.EventSnapShot.WaitOne(0, false))
					{

						byte[] buffer = (byte[])snapshotListener.UdpQueue.Dequeue();

						OpenFAST.Message msg = Common.Decode2Msg(buffer);
						if (msg != null && !msg.Template.Name.Contains("MDQuoteRequest") && !msg.Template.Name.Contains("MDHeartbeat") && !msg.Template.Name.Contains("MDSecurityStatus") && !msg.Template.Name.Contains("MDSecurityDefinition"))
						{
							string tempSecurityID = msg.GetValue("SecurityID").ToString();
							snapshotCount = int.Parse(msg.GetValue("TotNumReports").ToString());
							OpenFAST.SequenceValue entries = msg.GetSequence("MDEntries");
							if (this.msgDic.Count < snapshotCount)
							{
								// 累积snapshot 值。
								if (!msgDic.ContainsKey(tempSecurityID))
								{
									msgDic[tempSecurityID] = msg;
									RsIncrementEventArgs tmpArgs = new RsIncrementEventArgs();
									tmpArgs.ChannelId = ChannelId;
									tmpArgs.Message = msg;
									lock (incrementDic)
									{
										if (incrementDic.ContainsKey(tempSecurityID))
										{
											tmpArgs.TradePrice = incrementDic[tempSecurityID].TradePrice;
											tmpArgs.TradeSize = incrementDic[tempSecurityID].TradeSize;
										}
										else
										{
											tmpArgs.TradePrice = string.Empty;
											tmpArgs.TradeSize = string.Empty;
										}
									}
									if (this.RS_IncrementDataReceived != null)
									{
										this.RS_IncrementDataReceived(this, tmpArgs);
									}
								}
								else
								{
									if (!entries.Equals(msgDic[tempSecurityID].GetSequence("MDEntries")))
									{
										msgDic[tempSecurityID] = msg;
										RsIncrementEventArgs tmpArgs = new RsIncrementEventArgs();
										tmpArgs.ChannelId = ChannelId;
										tmpArgs.Message = msg;
										lock (incrementDic)
										{
											if (incrementDic.ContainsKey(tempSecurityID))
											{
												tmpArgs.TradePrice = incrementDic[tempSecurityID].TradePrice;
												tmpArgs.TradeSize = incrementDic[tempSecurityID].TradeSize;
											}
											else
											{
												tmpArgs.TradePrice = string.Empty;
												tmpArgs.TradeSize = string.Empty;
											}
										}
										if (this.RS_IncrementDataReceived != null)
										{
											this.RS_IncrementDataReceived(this, tmpArgs);
										}
									}
								}
							}
							else
							{
								if (!entries.Equals(msgDic[tempSecurityID].GetSequence("MDEntries")))
								{
									msgDic[tempSecurityID] = msg;
									RsIncrementEventArgs tmpArgs = new RsIncrementEventArgs();
									tmpArgs.ChannelId = ChannelId;
									tmpArgs.Message = msg;
									lock (incrementDic)
									{
										if (incrementDic.ContainsKey(tempSecurityID))
										{
											tmpArgs.TradePrice = incrementDic[tempSecurityID].TradePrice;
											tmpArgs.TradeSize = incrementDic[tempSecurityID].TradeSize;
										}
										else
										{
											tmpArgs.TradePrice = string.Empty;
											tmpArgs.TradeSize = string.Empty;
										}
									}
									if (this.RS_IncrementDataReceived != null)
									{
										this.RS_IncrementDataReceived(this, tmpArgs);
									}
								}
							}
						}
					}
					// Send message
					RsInfoEventArgs infoArgs = new RsInfoEventArgs();
					infoArgs.ChannelId = ChannelId;
					infoArgs.Message = "Sanpshot decode thread stoped!";
					if (this.RS_InfoReceived != null)
					{
						this.RS_InfoReceived(this, infoArgs);
					}
				}

			}
			catch (Exception ex)
			{
				RsErrorEventArgs args = new RsErrorEventArgs();
				args.ChannelId = ChannelId;
				args.Message += "StackTrace:" + ex.StackTrace;
				args.Message += "\r\nMessage:" + ex.Message;
				args.Message += "\r\nInnerException:" + ex.InnerException;
				if (this.RS_ErrorReceived != null)
				{
					this.RS_ErrorReceived(this, args);
				}
			}
		}

		// 匹配 Sanpshot 和Increment 数据。获取所有Sanpshot
		protected void MatchData(Object obj)
		{
			try
			{
				lock (obj)
				{
					// 获取 Sanpshot 的值
					OpenFAST.Message snapMsg = (OpenFAST.Message)obj;
					string key = snapMsg.GetValue("MsgSeqNum").ToString();
					string lstSeq = snapMsg.GetValue("LastMsgSeqNumProcessed").ToString();
					string rptSeq = snapMsg.GetValue("RptSeq").ToString();
					if (matchedFlag == false)
					{
						#region 匹配
						if (0 < this.incrementQueue.Count)
						{
							// 获取 Increment 的值
							OpenFAST.Message incrementMsg = (OpenFAST.Message)this.incrementQueue.Peek();
							string incrementSeq = incrementMsg.GetValue("MsgSeqNum").ToString();
							OpenFAST.SequenceValue entries = null;
							if (int.Parse(lstSeq) > int.Parse(incrementSeq))// 取 下一个 increment 值 ，直到相等
							{
								while (this.incrementQueue.Count > 0)
								{
									incrementMsg = (OpenFAST.Message)this.incrementQueue.Dequeue();
									incrementSeq = incrementMsg.GetValue("MsgSeqNum").ToString();
									if (lstSeq == incrementSeq)
									{
										break;
									}
								}
							}
							if (lstSeq == incrementSeq)
							{
								// 匹配第二个值， 先把 Increment 的 rptseq 值全部取出来

								entries = incrementMsg.GetSequence("MDEntries");
								string incrementRepSeq = ",";
								for (int i = 0; i < entries.Length; i++)
								{
									OpenFAST.GroupValue group = entries.Values[i];
									object seqObj = group.GetValue("RptSeq");
									if (seqObj != null)
									{
										incrementRepSeq += group.GetValue("RptSeq").ToString() + ",";
									}
								}
								// 俩者匹配
								if (-1 != incrementRepSeq.IndexOf("," + rptSeq + ","))
								{
									// 匹配成功
									RsInfoEventArgs infoArgs = new RsInfoEventArgs();
									infoArgs.ChannelId = ChannelId;
									infoArgs.Message = DateTime.Now.ToString() + "Matched:" + lstSeq + "|" + rptSeq +
																							" IncementMsgSeqNum:" + incrementSeq + "|" + incrementRepSeq;
									if (this.RS_InfoReceived != null)
									{
										this.RS_InfoReceived(this, infoArgs);
									}
									string tempSecurityID = snapMsg.GetValue("SecurityID").ToString();
									snapshotDicList.Add(tempSecurityID);
									// 向客户端发出第一个 Sanpshot数据
									RsSnapshotEventArgs args = new RsSnapshotEventArgs();
									args.ChannelId = ChannelId;
									args.Key = tempSecurityID;
									args.Message = snapMsg;
									if (this.RS_SnapShotDataReceived != null)
									{
										this.RS_SnapShotDataReceived(this, args);
									}
									snapshotCount = int.Parse(snapMsg.GetValue("TotNumReports").ToString());
									matchedFlag = true;
									//  向客户端发出一个 Sanpshot 的 总数信息
									infoArgs.Message = "Sanpshot size is:" + snapshotCount.ToString();
									if (this.RS_InfoReceived != null)
									{
										this.RS_InfoReceived(this, infoArgs);
									}
									return;
								}
							}
							// Sanpshot seq 小于 increment seq 时 Sanpshot seq 去下一个值, 放弃当次计算。
						}
						#endregion
					}
					else
					{
						#region 獲取所有 snapshot
						// 匹配成功后开始累积其值
						if (this.snapshotDicList.Count < snapshotCount)
						{
							// 累积snapshot 值。
							string tempSecurityID = snapMsg.GetValue("SecurityID").ToString();
							if (!snapshotDicList.Contains(tempSecurityID))
							{
								//snapshotDic.Add(int.Parse(tempSecurityID), snapMsg);
								snapshotDicList.Add(tempSecurityID);
								// Send message
								RsSnapshotEventArgs args = new RsSnapshotEventArgs();
								args.ChannelId = ChannelId;
								args.Key = tempSecurityID;
								args.Message = snapMsg;
								if (this.RS_SnapShotDataReceived != null)
								{
									this.RS_SnapShotDataReceived(this, args);
								}
							}
						}
						else
						{
							snapshotCompleted = true;
							StopDownloadSnapshot();
							RsStatusEventArgs args = new RsStatusEventArgs();
							args.ChannelId = ChannelId;
							args.Message = HandlerState.BooksResynchronizationFinished.ToString();
							if (this.RS_StatusChanged != null)
							{
								this.RS_StatusChanged(this, args);
							}
						}

						#endregion
					}

				}
			}
			catch (Exception ex)
			{
				RsErrorEventArgs args = new RsErrorEventArgs();
				args.ChannelId = ChannelId;
				args.Message += "StackTrace:" + ex.StackTrace;
				args.Message += "\r\nMessage:" + ex.Message;
				args.Message += "\r\nInnerException:" + ex.InnerException;
				if (this.RS_ErrorReceived != null)
				{
					this.RS_ErrorReceived(this, args);
				}
			}
		}

		protected void RecieveIncrementData()
		{
			// Decode the buffer

			incrementDataThread = new Thread(new ThreadStart(this.DecodeIncrementDataQueue));
			//incrementDataThread.IsBackground = true;
			incrementDataThread.Start();
		}

		protected void RecieveSecurityDefinition()
		{
			lock (this)
			{
				// Receive scurity defination
				ConnectionInfo address = Common.GetAllAddress(ChannelId, CHANNELTYPE.N);
				securityDefinitionListener = new Listener(CHANNELTYPE.N.ToString(), address, waitFlag.EventScuiryDefinition);
				securityDefinitionListener.Start();
				waitFlag.EventScuiryDefinition.Set();
				// Decode the buffer

				securityDefinitionThread = new Thread(new ThreadStart(this.DecodeSecurityDefinitionQueue));
				//securityDefinitionThread.IsBackground = true;
				securityDefinitionThread.Start();
			}
		}

		protected void RecieveSnapShotData()
		{
			snapshotThread = new Thread(new ThreadStart(this.DecodeSnapshotDataQueue));
			snapshotThread.Start();
		}

		// Start to receive security definition
		protected void StartDownloadIncrementData()
		{
			// Get Increment data
			RecieveIncrementData();
		}

		// Start to receive security definition
		protected void StartDownloadSnapshot()
		{
			// Set status
			RsStatusEventArgs args = new RsStatusEventArgs();
			args.ChannelId = ChannelId;
			args.Message = HandlerState.BooksResynchronizationStarted.ToString();
			if (this.RS_StatusChanged != null)
			{
				this.RS_StatusChanged(this, args);
			}
			// Get Snapshot data
			RecieveSnapShotData();
		}

		// Stop receive packge
		protected void StopDownloadIncrementData()
		{
			waitFlag.EventIncremntData.Reset();
			Thread.Sleep(1000);
			incrementDataListener.UdpQueue.Clear();
		}

		// Stop receive packge
		protected void StopDownloadSecurityDefinition()
		{
			Thread thread = new Thread(new ThreadStart(this.StopListenSecurityDefinition));
			thread.Start();
			thread.Join();
			Thread.Sleep(1000);
			securityDefinitionListener.UdpQueue.Clear();
			tempSecurityCount = 0;
			securityDefinitionDicString = ",";
			securityCount = 0;
		}

		// Stop receive packge
		protected void StopDownloadSnapshot()
		{
			Thread thread = new Thread(new ThreadStart(this.StopListenSnapshot));
			thread.Start();
			thread.Join();
			Thread.Sleep(1000);
			snapshotListener.UdpQueue.Clear();
			snapshotDicList.Clear();
			snapshotCount = 0;
		}

		protected void StopListen()
		{
			connectFlag = false;
			foreach (EventWaitHandle item in waitFlag.EventList)
			{
				item.Reset();
			}
		}

		protected void StopListenSecurityDefinition()
		{
			waitFlag.EventScuiryDefinition.Reset();
		}

		protected void StopListenSnapshot()
		{
			waitFlag.EventSnapShot.Reset();
		}


	}
}